import store from '@/store'

// 获取设备缩放比
const detectZoom = () => {
  let ratio = 0
  const screen = window.screen
  const ua = navigator.userAgent.toLowerCase()
  if (window.devicePixelRatio !== undefined) {
    ratio = window.devicePixelRatio
  } else if (~ua.indexOf('msie')) {
    if (screen.deviceXDPI && screen.logicalXDPI) {
      ratio = screen.deviceXDPI / screen.logicalXDPI
    }
  } else if (
    window.outerWidth !== undefined &&
    window.innerWidth !== undefined
  ) {
    ratio = window.outerWidth / window.innerWidth
  }
  if (ratio) {
    ratio = Math.round(ratio * 100)
  }
  return ratio
}

export const getRealVw = () => {
  const m = detectZoom()
  const ratioNum = store.getters.windowScale
  return ratioNum ? window.innerWidth * (Number(m) / (100 * ratioNum)) : window.innerWidth
}
export const getRealVh = () => {
  const m = detectZoom()
  const ratioNum = store.getters.windowScale
  return ratioNum ? window.innerHeight * (Number(m) / (100 * ratioNum)) : window.innerHeight
}

/**
 * 设置系统的缩放比例
 */
const setZoom = () => {
  const m = detectZoom()
  const ratioNum = store.getters.windowScale
  document.body.style.zoom = ratioNum ? ratioNum * 100 / Number(m) : null
  document.body.style.setProperty('--zoomVh', getRealVh() + 'px')
  document.body.style.setProperty('--zoomVw', getRealVw() + 'px')
}

export function handleResetPixelRatio () {
  setZoom()
  window.addEventListener('resize', setZoom)
}

// 设置缩放
export const setScale = async (scale) => {
  await store.dispatch('app/setWindowScale', scale)
  setZoom()
}
